package com.changgou.goods.controller;

import com.changgou.entity.PageResult;
import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.goods.service.BrandService;
import com.changgou.pojo.Brand;
import com.github.pagehelper.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * @Author: cxy
 * @Date: 2020/10/30 11:08
 * @Desc: 无
 * @Version: 1.0.0
 */
@RestController
@RequestMapping("/brand")
public class BrandController {


    @Autowired
    private BrandService brandService;


    @GetMapping("/findAll")
    public Result<Brand> findAll(){

        List<Brand> brandList = brandService.findAll();

        if(CollectionUtils.isEmpty(brandList)){
            brandList = Collections.EMPTY_LIST;
        }


        return new Result<>(true, StatusCode.OK, "查询所有品牌成功", brandList);
    }


    @GetMapping("/{id}")
    public Result<Brand> findById(@PathVariable Integer id){
        if(id.intValue() < 0){
            return new Result<>(true, StatusCode.ERROR, "根据id查询品牌失败, 参数不合法");
        }

        Brand brand = brandService.findById(id.intValue());
        return new Result<>(true, StatusCode.OK, "根据id查询品牌成功", brand);
    }


    @PostMapping
    public Result add(@RequestBody Brand brand){
        brandService.addBrand(brand);

        return new Result(true, StatusCode.OK, "新增品牌成功");
    }

    @PutMapping
    public Result update(@RequestBody Brand brand){
        brandService.updateBrand(brand);

        return new Result(true, StatusCode.OK, "更新品牌成功");
    }

    @DeleteMapping("{id}")
    public Result delete(@PathVariable Integer id){
        brandService.deleteBrand(id);

        return new Result(true, StatusCode.OK, "删除品牌成功");
    }


    @GetMapping("/searchPage/{pageNo}/{pageSize}")
    public Result selectPageAndCondition(@RequestParam Map<String, String> condition, @PathVariable int pageNo, @PathVariable int pageSize){
        Page<Brand> page = brandService.selectPageAndCondition(condition, pageNo, pageSize);

        PageResult<Brand> pageResult = new
                PageResult<>(page.getTotal(), page.getResult());

        return new Result(true, StatusCode.OK, "分页查询品牌成功", pageResult);
    }

}
